package com.rabbit.videoplayer.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.rabbit.videoplayer.R;
import com.rabbit.videoplayer.SpeedValue;
import com.rabbit.videoplayer.response.AliyunShowMoreValue;
import com.rabbit.videoplayer.response.PlayerType;
import com.rabbit.videoplayer.response.VideoPlayModel;
import com.rabbit.videoplayer.tools.Constants;
import com.rabbit.videoplayer.tools.VideoPlayerSPUtil;


public class ShowMoreView extends LinearLayout implements RadioGroup.OnCheckedChangeListener {

    // 亮度
    private SeekBar seekLight;
    private TextView tvDecoderTitle;
    // 音量
    private SeekBar seekVoice;
    // 倍速
    private RadioGroup rgSpeed;
    // 缩放
    private RadioGroup scaleModelRadioGroup;
    // 循环
    private RadioGroup loopPlayRadioGroup;
    private RadioGroup loopDecoderRadioGroup;
    private RadioGroup playerRadioGroup;
    private TextView tvDialogCancel;
    private TextView tvScaleTitleTip;
    private ScrollView scrollView;
    private OnMoreViewCheckedChangedListener mOnMoreViewCheckedChangedListener;
    private OnLightSeekChangeListener mOnLightSeekChangeListener;
    private OnShowMoreViewDisplayListener mOnVoiceSeekChangeListener;
    private OnTouchDownListener mOnTouchDownListener;
    private RadioButton rbHardDecoder;
    private RadioButton rbSoftDecoder;

    private final AudioManager audioManager;
    private final int maxVolume;
    private int playerModel;

    private int currentPlayerType;
    private int userSpecifiedPlayerType;

    public ShowMoreView(Context context) {
        super(context);
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        init(context);
    }

    private void init(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.veiw_wb_mix_dialog_more, this, true);
        findAllViews(view);
    }


    private void findAllViews(View view) {
        scrollView = view.findViewById(R.id.scrollView);
        seekLight = view.findViewById(R.id.seek_light);
        seekVoice = view.findViewById(R.id.seek_voice);
        rgSpeed = findViewById(R.id.alivc_rg_speed);
        loopPlayRadioGroup = view.findViewById(R.id.alivc_rg_loop);
        scaleModelRadioGroup = view.findViewById(R.id.alivc_rg_scale_model);
        loopDecoderRadioGroup = view.findViewById(R.id.alivc_rg_decoder);
        rbHardDecoder = view.findViewById(R.id.rb_loop_hard);
        rbSoftDecoder = view.findViewById(R.id.rb_loop_soft);
        playerRadioGroup = view.findViewById(R.id.rg_player_type);
        tvDecoderTitle = view.findViewById(R.id.tv_player_decoder_title);
        tvDialogCancel = view.findViewById(R.id.tv_dialog_cancel);
        tvScaleTitleTip = view.findViewById(R.id.tv_scale_model_title);

        tvDialogCancel.setOnClickListener(v -> {
            if (mOnMoreViewCheckedChangedListener != null) {
                mOnMoreViewCheckedChangedListener.onHideDialog();
            }
        });


    }

    public void configViews(AliyunShowMoreValue moreValue) {
        // 每次显示都让scrollView滑动到头部
        scrollTo(0, 0);
        if (moreValue == null) {
            return;
        }

        playerModel = moreValue.getPlayerModel();
        if (playerModel == VideoPlayModel.SKITS) {
            tvDialogCancel.setVisibility(View.VISIBLE);
        } else  {
            tvDialogCancel.setVisibility(View.GONE);
        }

        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekVoice.setMax(maxVolume);
        seekVoice.setProgress(currentVolume);
        seekLight.setProgress(moreValue.getScreenBrightness());
        float speed = moreValue.getSpeed();
        int index;
        if (speed == SpeedValue.Half.getValue()) {
            index = 0;
        } else if (speed == SpeedValue.One.getValue()) {
            index = 1;
        } else if (speed == SpeedValue.OneQuartern.getValue()) {
            index = 2;
        } else if (speed == SpeedValue.OneHalf.getValue()) {
            index = 3;
        } else if (speed == SpeedValue.Twice.getValue()) {
            index = 4;
        } else {
            index = 5;
        }
        // 速度
        rgSpeed.check(rgSpeed.getChildAt(index).getId());
        int currentScaleMode = moreValue.getScaleMode();
        int currentScaleModeIndex;
        if (currentScaleMode == Constants.VIDEO_RESIZE_FIT) {
            currentScaleModeIndex = 0;
        } else if (currentScaleMode == Constants.VIDEO_RESIZE_169) {
            currentScaleModeIndex = 1;
        } else if (currentScaleMode == Constants.VIDEO_RESIZE_43) {
            currentScaleModeIndex = 2;
        } else {
            currentScaleModeIndex = 3;
        }


        // 比例
        if (playerModel == VideoPlayModel.SKITS) {
            tvScaleTitleTip.setVisibility(View.GONE);
            scaleModelRadioGroup.setVisibility(View.GONE);
        } else  {
            tvScaleTitleTip.setVisibility(View.VISIBLE);
            scaleModelRadioGroup.setVisibility(View.VISIBLE);
            scaleModelRadioGroup.check(scaleModelRadioGroup.getChildAt(currentScaleModeIndex).getId());
        }

        // 是否循环播放
        loopPlayRadioGroup.check(loopPlayRadioGroup.getChildAt(moreValue.isLoop() ? 0 : 1).getId());
        // 解码
        if (VideoPlayerSPUtil.Companion.getInstance().getPlayerType() == PlayerType.MEDIA3) {
            loopDecoderRadioGroup.setVisibility(View.GONE);
            tvDecoderTitle.setVisibility(View.GONE);
        } else  {
            tvDecoderTitle.setVisibility(View.VISIBLE);
            loopDecoderRadioGroup.setVisibility(View.VISIBLE);
            // 软硬解
            boolean decoderType = VideoPlayerSPUtil.Companion.getInstance().isEnableHardDecoder();
            if (decoderType) {
                rbHardDecoder.setChecked(true);
            } else  {
                rbSoftDecoder.setChecked(true);
            }
        }


        // 播放器核心
        int playerCount = 3;
        VideoPlayerSPUtil spUtil = VideoPlayerSPUtil.Companion.getInstance();
        RadioButton aliRB = playerRadioGroup.findViewById(R.id.rb_ali);
        RadioButton txRB = playerRadioGroup.findViewById(R.id.rb_tx);
        RadioButton exoRB = playerRadioGroup.findViewById(R.id.rb_exo);
        // 不允许使用阿里播放器
        if (!spUtil.isAllowUseAliPlayer()) {
            // 隐藏播放器按钮
            aliRB.setVisibility(View.GONE);
            // 播放器数量-1
            playerCount -= 1;
        } else { // 显示播放器
            aliRB.setVisibility(View.VISIBLE);
        }
        // 不允许使用tx播放器
        if (!spUtil.isAllowUseTXPlayer()) {
            // 隐藏播放器按钮
            txRB.setVisibility(View.GONE);
            // 播放器数量-1
            playerCount -= 1;
        } else { // 显示播放器
            txRB.setVisibility(View.VISIBLE);
        }
        // exo播放器是必须的，所以一定会显示
        exoRB.setVisibility(View.VISIBLE);

        // 当前的播放器类型
        currentPlayerType = moreValue.getCurrentPlayerType();
        // 指定的播放器
        userSpecifiedPlayerType = moreValue.getUserSpecifiedPlayerType();
        // 是否隐藏其他播放器
        boolean isHideOtherPlayers = moreValue.isHideOtherPlayers();

        // 根据 #currentPlayerType 设置对应播放器为选中状态
        if (currentPlayerType == PlayerType.ALIYUN) {
            if (isHideOtherPlayers) {
                if (exoRB.getVisibility() != View.GONE) {
                    exoRB.setVisibility(View.GONE);
                    // 播放器数量-1
                    playerCount -= 1;
                }
                if (txRB.getVisibility() != View.GONE) {
                    txRB.setVisibility(View.GONE);
                    // 播放器数量-1
                    playerCount -= 1;
                }
            }

            if (!aliRB.isChecked()) {
                aliRB.setChecked(true);
            }
        } else if (currentPlayerType == PlayerType.TX) {
            if (isHideOtherPlayers) {
                if (aliRB.getVisibility() != View.GONE) {
                    aliRB.setVisibility(View.GONE);
                    // 播放器数量-1
                    playerCount -= 1;
                }
                if (exoRB.getVisibility() != View.GONE) {
                    exoRB.setVisibility(View.GONE);
                    // 播放器数量-1
                    playerCount -= 1;
                }
            }

            if (!txRB.isChecked()) {
                txRB.setChecked(true);
            }
        } else  {
            if (isHideOtherPlayers) {
                if (aliRB.getVisibility() != View.GONE) {
                    aliRB.setVisibility(View.GONE);
                    // 播放器数量-1
                    playerCount -= 1;
                }
                if (txRB.getVisibility() != View.GONE) {
                    txRB.setVisibility(View.GONE);
                    // 播放器数量-1
                    playerCount -= 1;
                }
            }
            if (!exoRB.isChecked()) {
                exoRB.setChecked(true);
            }
        }


        Log.e("ShowMoreView", "playerCount: " + playerCount);
        playerRadioGroup.setWeightSum(playerCount);

        addListener();
    }


    @SuppressLint("ClickableViewAccessibility")
    private void addListener() {
        rgSpeed.setOnCheckedChangeListener(this);
        loopPlayRadioGroup.setOnCheckedChangeListener(this);
        scaleModelRadioGroup.setOnCheckedChangeListener(this);
        loopDecoderRadioGroup.setOnCheckedChangeListener(this);
        playerRadioGroup.setOnCheckedChangeListener(this);
        seekLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (mOnVoiceSeekChangeListener != null) {
                    mOnVoiceSeekChangeListener.onCancelDelayHide();
                }
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mOnLightSeekChangeListener != null) {
                    mOnLightSeekChangeListener.onProgress(seekBar, progress, fromUser);
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mOnVoiceSeekChangeListener != null) {
                    mOnVoiceSeekChangeListener.onStartDelayHide();
                }
            }
        });

        seekVoice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (mOnVoiceSeekChangeListener != null) {
                    mOnVoiceSeekChangeListener.onCancelDelayHide();
                }
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mOnVoiceSeekChangeListener != null) {
                    mOnVoiceSeekChangeListener.onStartDelayHide();
                }
            }
        });

        scrollView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (mOnTouchDownListener != null) {
                    mOnTouchDownListener.onTouchDown();
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (mOnTouchDownListener != null) {
                    mOnTouchDownListener.onTouchUp();
                }
            }
            return false;
        });
    }



    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (mOnMoreViewCheckedChangedListener == null) return;
        if (group == rgSpeed) {
            SpeedValue speedValue;
            if (checkedId == R.id.rb_speed_half) {
                speedValue = SpeedValue.Half;
            } else if (checkedId == R.id.rb_speed_normal) {
                speedValue = SpeedValue.One;
            } else if (checkedId == R.id.rb_speed_onequartern) {
                speedValue = SpeedValue.OneQuartern;
            } else if (checkedId == R.id.rb_speed_onehalf) {
                speedValue = SpeedValue.OneHalf;
            } else  if (checkedId == R.id.rb_speed_twice) {
                speedValue = SpeedValue.Twice;
            } else  {
                speedValue = SpeedValue.Third;
            }
            mOnMoreViewCheckedChangedListener.onSpeedChanged(speedValue);
        } else if (group == scaleModelRadioGroup) { // 缩放
            int mScaleMode;
            if (checkedId == R.id.rb_scale_to_fill) {
                mScaleMode = Constants.VIDEO_RESIZE_FILL;
            } else if (checkedId == R.id.rb_scale_169) {
                mScaleMode = Constants.VIDEO_RESIZE_169;
            } else if (checkedId == R.id.rb_scale_43) {
                mScaleMode = Constants.VIDEO_RESIZE_43;
            } else {
                mScaleMode = Constants.VIDEO_RESIZE_FIT;
            }
            mOnMoreViewCheckedChangedListener.onScaleModeChanged(mScaleMode);
        } else if (group == loopPlayRadioGroup) {
            mOnMoreViewCheckedChangedListener.onLoopChanged(checkedId == R.id.rb_loop_open);
        } else if (group == loopDecoderRadioGroup) {
            // 修改软硬解
            mOnMoreViewCheckedChangedListener.onDecoderChanged(checkedId == R.id.rb_loop_hard);
        } else if (group == playerRadioGroup) {
            int type;
            if (checkedId == R.id.rb_ali) {
                type = PlayerType.ALIYUN;
            } else if (checkedId == R.id.rb_tx) {
                type = PlayerType.TX;
            } else  {
                type = PlayerType.MEDIA3;
            }
            mOnMoreViewCheckedChangedListener.onPlayerChanged(type);
        }
    }


    public interface OnMoreViewCheckedChangedListener {
        /**
         * 比例切换
         */
        void onScaleModeChanged(int mScaleMode);

        /**
         * 速度切换
         */
        void onSpeedChanged(SpeedValue speedValue);
        /**
         *  是否循环
         */
        void onLoopChanged(boolean isLoop);
        void onDecoderChanged(boolean isHardDecoder);
        void onPlayerChanged(int type);
        void onHideDialog();
    }

    public void setOnMoreViewCheckedChangedListener(OnMoreViewCheckedChangedListener listener) {
        this.mOnMoreViewCheckedChangedListener = listener;
    }


    public interface OnTouchDownListener {
        void onTouchDown();
        void onTouchUp();
    }

    public void setOnTouchDownListener(OnTouchDownListener listener) {
        this.mOnTouchDownListener = listener;
    }

    /**
     * 亮度调节
     */
    public interface OnLightSeekChangeListener {
        void onProgress(SeekBar seekBar, int progress, boolean fromUser);
    }

    public void setOnLightSeekChangeListener(OnLightSeekChangeListener listener) {
        this.mOnLightSeekChangeListener = listener;
    }

    /**
     * 音量调节
     */
    public interface OnShowMoreViewDisplayListener {
        void onCancelDelayHide();
        void onStartDelayHide();
    }

    public void setOnShowMoreViewDisplayListener(OnShowMoreViewDisplayListener listener) {
        this.mOnVoiceSeekChangeListener = listener;
    }

    /**
     * 设置音量
     */
    public void setVoiceVolume(float volume) {
        if (seekVoice != null) {
            seekVoice.setProgress((int) (volume * 100));
        }
    }

    /**
     * 设置亮度
     */
    public void setBrightness(int value) {
        if (seekLight != null) {
            seekLight.setProgress(value);
        }
    }
}

